import React, { PureComponent, Fragment } from 'react';
import { routerRedux,Link } from 'dva/router';
import { connect } from 'dva';
import moment from 'moment';
import BusinessModal from './BusinessModal';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Checkbox,
  Table,
  Popconfirm,
} from 'antd';

import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import Authorized from '../../utils/Authorized';
import defaultAvatar from '../../assets/admin_logo.png';
import styles from './UserList.less';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['关闭', '运行中', '已上线', '异常'];

@connect(({ businessList, loading }) => ({
  businessList,
  loading: loading.models.businessList,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    addInputValue: '',
    checkedGroupList: [],
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'businessList/fetch',
    });
    dispatch({
      type : 'businessList/fetchGroup',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      startIndex: (pagination.current - 1) * pagination.pageSize, //此处峻吉分页需要是第一项的序号，如第二页传10，而不是具体的分页码1，2，3
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'businessList/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'businessList/fetch',
      payload: {},
    });
  };

  toggleForm = () => {
    this.setState({
      expandForm: !this.state.expandForm,
    });
  };

  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;

    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'businessList/remove',
          payload: {
            no: selectedRows.map(row => row.no).join(','),
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'businessList/fetch',
        payload: values,
      });
    });
  };

  handleModalVisible = flag => {
      this.props.form.resetFields();
        this.setState({
          modalVisible: !!flag,
        });
  };

  handleAdd = fields => {
    this.props.dispatch({
      type: 'businessList/add',
      payload: {
        description: fields.desc,
      },
    });

    message.success('添加成功');
    this.setState({
      modalVisible: false,
    });
  };

  bindChangeStatus = (id,action)=>{
    const { dispatch } = this.props;
    dispatch({
      type: 'businessList/changeStatus',
      payload: {
        user_id: id,
        action: action
      }
    });
  }

  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    const { group } = this.props.businessList;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="手机号码">
              {getFieldDecorator('phone')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="微信昵称">
              {getFieldDecorator('nickname')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="购买次数">
              {getFieldDecorator('buy_count')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="1">1+</Option>
                  <Option value="2">2+</Option>
                  <Option value="5">5+</Option>
                  <Option value="10">10+</Option>
                  <Option value="20">20+</Option>
                  <Option value="50">50+</Option>
                </Select>
              )}
            </FormItem>
          </Col>

        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="分组名称">
              {getFieldDecorator('groups')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="">请选择</Option>
                  {
                    group.forEach((v, i)=>{
                      return <Option value={v} key={`group_${i}`}>{ v }</Option>
                    })
                  }
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }
  

  handleSelectGroup = row=>{
    console.log('row',[row]);
    let groups = [];  //计算出当前已有分组ID值
    this.props.businessList.group.forEach(v=>{
      row.groups.forEach(s=>{
        if(v.name == s){
          groups.push(v.name);
        }
      })
    });

    this.setState({
      modalVisible: true,
      selectedRows : [row],
      checkedGroupList: groups,
    });
  };

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    console.log(this.props);
    const { businessList: { data, group }, loading } = this.props;
    const { selectedRows, modalVisible, addInputValue, checkedGroupList } = this.state;


    const columns = [
      {
        title: '头像',
        render:(val,record)=>{
          return <img src={record.userInfo.headUrl || defaultAvatar} width="30" height={30} />
        }
      },
      {
        title: '账号',
        render:(val,record)=>{
          return record.userInfo.username
        }
      },
      {
        title: '昵称',
        render:(val,record)=>{
          return record.userInfo.nickname
        }
      },
      {
        title: '邮箱',
        render:(val,record)=>{
          return record.email || record.userInfo.email
        }
      },
      {
        title: '结算信息',
        dataIndex: 'settlement_info',
        render: (text, record)=>{
          return JSON.stringify(text);
        }
      },
      {
        title: '操作',
        render: (text, record) => (
          <Fragment>
            <Popconfirm title="你确定要取消此商家资格？" okText="确定" cancelText="取消" onConfirm={()=>{ this.bindChangeStatus(record.userId, 0) }}>
            <a href="javascript:;" >取消资格</a>
            </Popconfirm>
          </Fragment>
        ),
      },
    ];

    return (
      <PageHeaderLayout title="商家列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            {/*<div className={styles.tableListForm}>{this.renderForm()}</div>*/}
            <div className={styles.tableListOperator}>
              
              <Button icon="plus" type="primary" onClick={this.handleModalVisible} >
                  新增商家
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Button>分组</Button>
                </span>
              )}
            </div>
            {/*  暂不需要分页<StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />*/}
            <Table
              loading={loading}
              rowKey={(record)=>`bussiness${record.userId}`}
              dataSource={data}
              columns={columns}
              pagination={false}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <BusinessModal modalVisible={modalVisible} handleModalVisible={this.handleModalVisible} />
      </PageHeaderLayout>
    );
  }
}
